import 'package:chathouse/model/pre_question_bean.dart';
import 'package:chathouse/model/response_bean.dart';
import 'package:chathouse/pages/questions/common_widget.dart';
import 'package:chathouse/pages/questions/extent.dart';
import 'package:chathouse/pages/questions/pre_question_page.dart';
import 'package:chathouse/public/Config.dart';
import 'package:chathouse/public/event_bus.dart';
import 'package:chathouse/widgets/base_appbar.dart';
import 'package:chathouse/widgets/form_widgets/area_select_widget7.dart';
import 'package:chathouse/widgets/form_widgets/image_picker_widget11.dart';
import 'package:chathouse/widgets/form_widgets/input_widget4.dart';
import 'package:chathouse/widgets/form_widgets/location_select_widget9.dart';
import 'package:chathouse/widgets/form_widgets/multiple_select_widget2.dart';
import 'package:chathouse/widgets/form_widgets/single_select_and_input_widget5.dart';
import 'package:chathouse/widgets/form_widgets/single_select_widget1.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:chathouse/util/base_utils.dart';
import '../../constant/app_constant.dart';
import '../../widgets/form_widgets/date_pick_widget8.dart';
import '../../widgets/form_widgets/drpo_down_widget3.dart';
import '../../widgets/form_widgets/multiple_select_and_input_widget6.dart';
import '../../widgets/form_widgets/single_select_and_input_widget12.dart';
import '../../widgets/form_widgets/time_pick_widget10.dart';
import 'package:intl/intl.dart';

import '../route_manager/root_route_manager.dart';

//問題頁
class NextQuestionPage extends StatefulWidget {
  int page;
  int serviceId;
  String serviceTitle;
  PreQuestionBeanTool preQuestionBeanTool;
  PreQuestionController preQuestionController;
  Color? titleColor;
  NextQuestionPage(this.page, this.serviceId, this.serviceTitle,
      this.preQuestionBeanTool, this.preQuestionController, this.titleColor,
      {Key? key})
      : super(key: key);

  @override
  State<NextQuestionPage> createState() => _NextQuestionPageState();
}

class _NextQuestionPageState extends State<NextQuestionPage> {
  List<Map> paras = []; //问题答案,下一页参数
  Map p6 = {}; //temp 类型6用的 保存答案
  Map p9 = {}; //temp 类型9用的 保存答案
  Map<int, dynamic> tempMap = {};
  late NextQuestionController controller;
  @override
  void initState() {
    super.initState();
    controller = NextQuestionController();
  }

  @override
  void dispose() {
    super.dispose();
    Obj.dismissLoading();
    controller.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: getAppBar(
            leading: IconButton(
                onPressed: () {
                  goToDetail();
                },
                icon: ImageUtils.image(Res.question_close,
                    width: 28.w, height: 28.w)),
            title:
                widget.preQuestionBeanTool.serviceName ?? widget.serviceTitle,
            titleColor: widget.titleColor ?? Colors.black),
        body: Column(
          children: [
            Expanded(child: ListView(children: getSubWidget())),
            Container(
              padding: EdgeInsets.only(
                  left: 26.w, right: 26.w, bottom: 20.w, top: 20.w),
              child: Obx(() {
                return Row(
                  children: [
                    Expanded(
                        child: Text("上頁",
                                style: getTextStyle(20.sp,
                                    color: Colors.white,
                                    fontType: FontType.BOLD))
                            .setContainer(
                                alignment: Alignment.center,
                                height: 38.w,
                                decoration: BoxDecoration(
                                    color: MyColors.gary_155155155,
                                    borderRadius: BorderRadius.all(
                                        Radius.circular(19.w))))
                            .setOnClickListener(() {
                      Get.back();
                    })),
                    SizedBox(width: 20.w),
                    Expanded(
                      child: Text(
                              (widget.preQuestionBeanTool.rows?.first
                                              .exhibition ??
                                          false) ==
                                      false
                                  ? "下一頁"
                                  : "提交",
                              style: getTextStyle(20.sp,
                                  color: Colors.white, fontType: FontType.BOLD))
                          .setContainer(
                              alignment: Alignment.center,
                              height: 38.w,
                              decoration: BoxDecoration(
                                  color: controller.canNextBtnClick.value
                                      ? ((widget.preQuestionBeanTool.rows?.first
                                                      .exhibition ??
                                                  false) ==
                                              false
                                          ? MyColors.brow_25118177
                                          : MyColors.red_2166474)
                                      : MyColors.gary_155155155,
                                  borderRadius:
                                      BorderRadius.all(Radius.circular(19.w))))
                          .setOnClickListener(() {
                        nextButtonClick();
                      }),
                    ),
                  ],
                );
              }),
            )
          ],
        ));
  }

  //14种问题
  List<Widget> getSubWidget() {
    return getCommandSubWidget(widget.preQuestionBeanTool, widget.serviceId,
        setNextButtonCanClick, paras, p6, p9, tempMap,
        page: widget.page);
  }

  void setNextButtonCanClick() {
    bool checkParas = true;
    for (var element in paras) {
      if (element["required"] == "0") {
        if (element["firstOptionCode"] == null ||
            element["firstOptionCode"] == "") {
          checkParas = false;
          debugPrint("${widget.preQuestionBeanTool.rows?.firstWhere((a) {
            return a.problemId == element["problemId"];
          }).problemName}");
        }
      }
    }
    controller.canNextBtnClick.value = checkParas;
  }

  void nextButtonClick() {
    if (!controller.canNextBtnClick.value) return;
    //最后一页提交
    if (widget.preQuestionBeanTool.rows?.first.exhibition != null &&
        !(widget.preQuestionBeanTool.rows?.first.exhibition == false)) {
      setSubmitParas();
      Obj.showLoading();

      Apis.nextPageSubmit(widget.preQuestionController.getFormatAppParas(), {
        "serviceId": widget.preQuestionBeanTool.serviceId ?? widget.serviceId
      }).then((response) {
        Obj.dismissLoading();
        try {
          ResponseBean resp = ResponseBean.fromJson(response?.data ?? {});
          if (resp.isRequestSuccess) {
            ToastUtil.showToast("操作成功");
            if (widget.preQuestionController.subSelectExpert != null) {
              widget.preQuestionController.subSelectExpert!(goToDetail);
            } else {
              goToDetail();
            }
          }
        } catch (e) {
          debugPrint(e.toString());
        }
      }).catchError((error) => {Obj.dismissLoading(), setState(() {})});

      return;
    }
    //下一页
    Obj.showLoading();
    Apis.nextPage(paras).then((response) {
      Obj.dismissLoading();
      try {
        var resQuestionBeanTool =
            PreQuestionBeanTool.fromJson(response?.data ?? {});
        if (resQuestionBeanTool.isRequestSuccess) {
          setSubmitParas();
          Get.to(
              NextQuestionPage(
                  widget.page + 1,
                  resQuestionBeanTool.serviceId ??
                      widget.preQuestionBeanTool?.serviceId ??
                      widget.serviceId,
                  resQuestionBeanTool.serviceName ??
                      widget.preQuestionBeanTool.serviceName ??
                      widget.serviceTitle,
                  resQuestionBeanTool,
                  widget.preQuestionController,
                  widget.titleColor),
              preventDuplicates: false);
        }
      } catch (e) {
        debugPrint(e.toString());
      }
    }).catchError((error) => {Obj.dismissLoading(), setState(() {})});
  }

  void goToDetail() {
    debugPrint("goToDetail");
    if (!Get.currentRoute.contains("PreQuestionPage")) {
      Get.back();
      goToDetail();
    } else {
      Get.back();
      //去訂單頁
      eventBus.fire(UpdateOrderListEvent());
      RootRouteController clientRootPageController = AppConstant.rootController;
      clientRootPageController.goClientOrderPage();
      return;
    }
  }

  void setSubmitParas() {
    debugPrint("page=${widget.page}");
    //配置 最后提交页 参数
    List<Map> tempList = [];
    for (var element in paras) {
      PreQuestionBean? preQuestionBean =
          widget.preQuestionBeanTool?.rows?.firstWhere((model) {
        return model.problemId == element["problemId"];
      });
      Map<String, dynamic> submitParas = {
        "optionCode": element["firstOptionCode"],
        "optionValue": element["optionValue"],
        "problemId": preQuestionBean?.problemId,
        "problemName": preQuestionBean?.problemName,
        "problemSort": preQuestionBean?.problemSort,
        "problemType": preQuestionBean?.problemType,
      };
      tempList.add(submitParas);
      // widget.preQuestionController.appParas.add(submitParas);
    }
    widget.preQuestionController.appParas[widget.page] = tempList;
  }
}

class NextQuestionController extends GetxController {
  var canNextBtnClick = false.obs;
}
